//
//  ADJgCustomAdapterTestUnifiedNativeAd.m
//  ADJgCustomPlatform
//
//  Created by Suancai on 2021/9/8.
//

#import "ADJgCustomAdapterGDTUnifiedNativeAd.h"
#import <GDTMobSDK/GDTUnifiedNativeAd.h>
#import <GDTMobSDK/GDTUnifiedNativeAdView.h>
#import <ADJgSDK/ADJgAdapterNativeAdData.h>
#import "ADJgCustomAdapterGDTUnifiedNativeAdView.h"

@interface ADJgCustomAdapterGDTUnifiedNativeAd ()<GDTUnifiedNativeAdDelegate,ADJgCustomAdapterGDTUnifiedNativeAdViewDelegate,GDTUnifiedNativeAdViewDelegate>
{
    ADJgCustomAdapterNativeRequestContext *_context;
    
    GDTUnifiedNativeAd *_unifiedNativeAdAd;
    
    NSMapTable<GDTUnifiedNativeAdDataObject *,ADJgCustomAdapterGDTUnifiedNativeAdView *> *_weakMap;
    
    GDTUnifiedNativeAdDataObject *_bidUnifiedNativeAdData;
    
    BOOL _isGdtBidding;
}
@end

@implementation ADJgCustomAdapterGDTUnifiedNativeAd

+ (void)load {
    [self registPlatformAdLoaderClass:self forSdkName:@"gdt" renderType:ADJgAdapterRenderTypeNative];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _weakMap = [NSMapTable weakToWeakObjectsMapTable];
    }
    return self;
}

// MARK: - Override

- (void)requestAdWithContext:(ADJgCustomAdapterNativeRequestContext *)context {
    _context = context;
    _isGdtBidding = NO;
    [self.unifiedNativeAdAd loadAdWithAdCount:_context.loadCount];
}

- (void)biddingRequestWithContext:(ADJgCustomAdapterNativeRequestContext *)context{
    _context = context;
    _isGdtBidding = YES;
    [self.unifiedNativeAdAd loadAdWithAdCount:_context.loadCount];
}

- (void)biddingResult:(ADJgSDKSourceBiddingResult)result AllPrice:(NSArray *)allPrices {
    // 获取一价二价
    NSNumber *winnerPrice = 0;
    NSNumber *secondPrice = 0;
    if (allPrices.count > 0) {
        NSNumber *firstPrice = allPrices.firstObject;
        // 聚合平台存储为单位为：分，GDT 是以元返回，同时也需要已元上报
        winnerPrice = [NSNumber numberWithFloat:firstPrice.floatValue * 100];
    }
    if (allPrices.count > 1) {
        NSNumber *tempSecondPrice = allPrices[1];
        secondPrice = [NSNumber numberWithFloat:tempSecondPrice.floatValue * 100];
    }
    switch (result) {
        case ADJgSDKSourceBiddingResult_Sucess:
            [self sendWinNotificationWithWinnerPrice:[NSNumber numberWithInteger:_bidUnifiedNativeAdData.eCPM] withSecondPrice:secondPrice];
            break;
        case ADJgSDKSourceBiddingResult_Failed:
            [self sendLossNotificationWithPrice:winnerPrice withRease:GDTAdBiddingLossReasonLowPrice withWinnerAdnID:@""];
            break;
        case ADJgSDKSourceBiddingResult_Timeout:
            [self sendLossNotificationWithPrice:@0 withRease:GDTAdBiddingLossReasonNoAd withWinnerAdnID:@""];
            break;
        default:
            [self sendLossNotificationWithPrice:@0 withRease:GDTAdBiddingLossReasonOther withWinnerAdnID:@""];
            break;
    }
}

/** 竞赢上报
 *  infoDic 字典类型，支持的key有
 *  GDT_M_W_E_COST_PRICE：竞胜价格 (单位: 分)，值类型为NSNumber *
 *  GDT_M_W_H_LOSS_PRICE：最高失败出价，值类型为NSNumber *
 */
- (void)sendWinNotificationWithWinnerPrice:(NSNumber *)winnerPrice withSecondPrice:(NSNumber *)secondPrice{
    if(winnerPrice == nil){
        return ;
    }
    
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    
    [infoDic setValue:winnerPrice forKey:GDT_M_W_E_COST_PRICE];
    if (secondPrice != nil) {
        [infoDic setValue:secondPrice forKey:GDT_M_W_H_LOSS_PRICE];
    }else{
        [infoDic setValue:@(0) forKey:GDT_M_W_H_LOSS_PRICE];
    }
    [_bidUnifiedNativeAdData sendWinNotificationWithInfo:infoDic.copy];
}
/**
 *  竞败之后或未参竞调用
 *
 *  infoDic 竞败信息，字典类型，支持的key有
 *  GDT_M_L_WIN_PRICE ：竞胜价格 (单位: 分)，值类型为NSNumber *，选填
 *  GDT_M_L_LOSS_REASON ：优量汇广告竞败原因，竞败原因参考枚举GDTAdBiddingLossReason中的定义，值类型为NSNumber *，必填
 *  GDT_M_ADNID  ：竞胜方渠道ID，值类型为NSString *，必填
 */
- (void)sendLossNotificationWithPrice:(NSNumber *)price withRease:(GDTAdBiddingLossReason)reason withWinnerAdnID:(NSString *)winnerAdnID{
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    [infoDic setValue:price forKey:GDT_M_L_WIN_PRICE];
    [infoDic setValue:@(reason) forKey:GDT_M_L_LOSS_REASON];
    [infoDic setValue:winnerAdnID forKey:GDT_M_ADNID];
    [_bidUnifiedNativeAdData sendLossNotificationWithInfo:infoDic.copy];
}


// MARK: - GDTUnifiedNativeAdDelegate

- (void)gdt_unifiedNativeAdLoaded:(NSArray<GDTUnifiedNativeAdDataObject *> * _Nullable)unifiedNativeAdDataObjects error:(NSError * _Nullable)error {
    if(error) {
        [self trackNativeAdFailToLoadWithError:error];
        return;
    }
    
    NSInteger price = 0;
    if (_isGdtBidding) {
        _bidUnifiedNativeAdData = unifiedNativeAdDataObjects.firstObject;
        price = _bidUnifiedNativeAdData.eCPM;
    }

    NSMutableArray<UIView<ADJgAdapterNativeAdViewDelegate> *> *adViewArray = [NSMutableArray new];
    for (GDTUnifiedNativeAdDataObject *dataObj in unifiedNativeAdDataObjects) {
        ADJgCustomAdapterGDTUnifiedNativeAdView *adView = [ADJgCustomAdapterGDTUnifiedNativeAdView new];
        adView.adData = dataObj;
        adView.delegate = self;
        adView.unifiedNativeAdDelegate = self;
        adView.viewController = _context.viewController;
        [adViewArray addObject:adView];
        [_weakMap setObject:adView forKey:dataObj];
        adView.adData.videoConfig.videoMuted = _context.muted;
    }
    
    [self trackNativeAdSucceedToLoadWithNativeAdViews:adViewArray ecpm:price/100];
}

// MARK: - GDTUnifiedNativeAdViewDelegate

- (void)gdt_unifiedNativeAdViewWillExpose:(GDTUnifiedNativeAdView *)unifiedNativeAdView {
    ADJgCustomAdapterGDTUnifiedNativeAdView *adView = [_weakMap objectForKey:unifiedNativeAdView.dataObject];
    [self trackNativeAdExposuredWithNativeView:adView];
}

- (void)gdt_unifiedNativeAdViewDidClick:(GDTUnifiedNativeAdView *)unifiedNativeAdView {
    ADJgCustomAdapterGDTUnifiedNativeAdView *adView = [_weakMap objectForKey:unifiedNativeAdView.dataObject];
    [self trackNativeAdClickedWithNativeView:adView];
}

- (void)gdt_unifiedNativeAdDetailViewClosed:(GDTUnifiedNativeAdView *)unifiedNativeAdView {
    ADJgCustomAdapterGDTUnifiedNativeAdView *adView = [_weakMap objectForKey:unifiedNativeAdView.dataObject];
    [self trackNativeAdLandingPageClosedWithNativeView:adView];
}

// MARK: - ADJgCustomAdapterUnifiedNativeAdViewDelegate

- (void)adjgCustomUnifiedNativeAdViewRender:(ADJgCustomAdapterGDTUnifiedNativeAdView *)adView {
    [self trackNativeAdRenderSucceedWithNativeView:adView];
}

- (void)adjgCustomUnifiedNativeAdViewClose:(ADJgCustomAdapterGDTUnifiedNativeAdView *)adView {
    [self trackNativeAdClosedWithNativeView:adView];
}



// MARK: - Lazy load

- (GDTUnifiedNativeAd *)unifiedNativeAdAd {
    if(!_unifiedNativeAdAd) {
        _unifiedNativeAdAd = [[GDTUnifiedNativeAd alloc] initWithPlacementId:_context.posId];
        _unifiedNativeAdAd.delegate = self;
    }
    return _unifiedNativeAdAd;
}

@end
